﻿using LdtJudge.DataEngine.Common.XmlUtility;
using LdtJudge.DataEngine.Model.DataModel.SysCommon;
using LdtJudge.DataEngine.Model.XMLConfigModel.OptimzeMode;
using LdtJudge.DataEngine.Model.XMLConfigModel.SameNodeConfigModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml;

namespace LdtDataEngin.ModuleDetail.BaseModule.MultiFack
{
    public class MultiFactDifference : MultiFactBase
    {
        /// <summary>
        /// 确定最后有异议的人员要素集合
        /// </summary>
        public Dictionary<Tuple<string, string>, XmlNode> DifferenceList = new Dictionary<Tuple<string, string>, XmlNode>();


        public CaseCauseModel caseCauseModel;
        /// <summary>
        /// 保存某人对某人的有异议要素
        /// </summary>
        public Dictionary<Tuple<string, string>, XmlNode> ptopDifferList = new Dictionary<Tuple<string, string>, XmlNode>();

        /// <summary>
        /// 提取有异议要素方法入口
        /// </summary>
        /// <param name="template">要素模板</param>
        /// <param name="personXml">优选数据集合</param>
        /// <param name="xmlConfigModels">配置文件集合</param>
        /// <param name="nodeHandleType">同节点判定类型</param>
        /// <returns></returns>
        public override string MultiFactHandleCommon(XmlNode template, Dictionary<Tuple<string, string>, XmlNode> personXml, List<SameNodeXml> xmlConfigModels, SameNodeHandleType nodeHandleType)
        {
            /////初始化合并对象
            MultiFactUnion multiFactuniondiff = new MultiFactUnion();
            //分人员取有异议
            Dictionary<Tuple<string, string>, List<XmlNode>> xmlDifferenceList = new Dictionary<Tuple<string, string>, List<XmlNode>>();
            //获取当前要取交集的数据集合
            if (personXml.Count > 1)
            {
                string nodename = template.Name;// "事实要素";
                string templatexml = string.Format("<{0}></{0}>", template.ParentNode.Name);

                if (caseCauseModel != null)
                {
                    templatexml = string.Format("<{0} 案由名称='{1}' 案由ID='{2}'></{0}>", template.ParentNode.Name, caseCauseModel.CC_Name, caseCauseModel.CC_ID);
                }
                //进行遍历分人员数据
                foreach (var person in personXml)
                {
                    List<XmlNode> documents = new List<XmlNode>();
                    var others = personXml.Where(a => a.Key != person.Key).ToList();
                    foreach (var other in others)
                    {
                        //新建一个此案由的根节点xml
                        XmlDocument result = new XmlDocument();
                        result.LoadXml(templatexml);
                        XmlNode xmlNodeFact = result.CreateElement("事实要素");
                        result.DocumentElement.AppendChild(xmlNodeFact);
                        this.CompareNode(template, person.Value, other.Value, xmlConfigModels, xmlNodeFact, nodeHandleType);
                        //去除空节点
                        result = XmlUtility.EscapeNodeIndexAndBlank(result);
                        if (result.OuterXml != templatexml)
                            documents.Add(result);

                        ptopDifferList.Add(new Tuple<string, string>(person.Key.Item1 + "-" + person.Key.Item2, other.Key.Item1 + "-" + other.Key.Item2), result);
                        dataContext.InteractiveShow.LogShow("\r\n       ▶（" + person.Key.Item1 + "-" + person.Key.Item2 + "）与（" + other.Key.Item1 + "-" + other.Key.Item2 + "）形成的有异议要素为：\r\n" + result.OuterXml);
                    }
                    if (documents.Count > 0)
                        xmlDifferenceList.Add(person.Key, documents);
                }
            }

            DifferenceList = multiFactuniondiff.MultiFactUnionPersonXml(template, xmlDifferenceList, xmlConfigModels, nodeHandleType);
            foreach (var persondiff in DifferenceList)
            {
                dataContext.InteractiveShow.LogShow("\r\n       ▶" + persondiff.Key.Item1 + "-" + persondiff.Key.Item2 + "合并后有异议要素为：\r\n" + persondiff.Value.OuterXml);
            }
            return "";
        }


        ///// <summary>
        ///// 提取有异议要素方法入口
        ///// </summary>
        ///// <param name="template">要素模板</param>
        ///// <param name="personXml">优选数据集合</param>
        ///// <param name="xmlConfigModels">配置文件集合</param>
        ///// <returns></returns>
        //public override string MultiFactHandleCommon(XmlNode template, Dictionary<Tuple<string, string>, XmlNode> personXml, List<OptimizeSameNodeXL> xmlConfigModels)
        //{
        //    /////初始化合并对象
        //    MultiFactUnion multiFactuniondiff = new MultiFactUnion() { Dytable = base.Dytable, InerActive = base.InerActive };
        //    //分人员取有异议
        //    Dictionary<Tuple<string, string>, List<XmlNode>> xmlDifferenceList = new Dictionary<Tuple<string, string>, List<XmlNode>>();
        //    //获取当前要取交集的数据集合
        //    if (personXml.Count > 1)
        //    {
        //        string nodename = template.Name;// "事实要素";
        //        string templatexml = string.Format("<{0}></{0}>", template.ParentNode.Name);
        //        //进行遍历分人员数据
        //        foreach (var person in personXml)
        //        {
        //            List<XmlNode> documents = new List<XmlNode>();
        //            var others = personXml.Where(a => a.Key != person.Key).ToList();
        //            foreach (var other in others)
        //            {
        //                //新建一个此案由的根节点xml
        //                XmlDocument result = new XmlDocument();
        //                result.LoadXml(templatexml);
        //                XmlNode xmlNodeFact = result.CreateElement("事实要素");
        //                result.DocumentElement.AppendChild(xmlNodeFact);
        //                CompareNode(template, person.Value, other.Value, xmlConfigModels, xmlNodeFact);
        //                //去除空节点
        //                result = base.EscapeNodeIndexAndBlank(result);
        //                if (result.OuterXml != templatexml)
        //                    documents.Add(result);
        //                base.InerActive.LogShow("\r\n       ▶（" + person.Key.Item1 + "-" + person.Key.Item2 + "）与（" + other.Key.Item1 + "-" + other.Key.Item2 + "）形成的有异议要素为：\r\n" + result.OuterXml);
        //            }
        //            if (documents.Count > 0)
        //                xmlDifferenceList.Add(person.Key, documents);
        //        }
        //    }

        //    DifferenceList = multiFactuniondiff.MultiFactUnionPersonXml(template, xmlDifferenceList, xmlConfigModels);
        //    foreach (var persondiff in DifferenceList)
        //    {
        //        base.InerActive.LogShow("\r\n       ▶" + persondiff.Key.Item1 + "-" + persondiff.Key.Item2 + "合并后有异议要素为：\r\n" + persondiff.Value.OuterXml);
        //    }
        //    return "";
        //}

        ///// <summary>
        ///// 进行节点的对比
        ///// </summary>
        ///// <param name="templateNode">模板节点</param>
        ///// <param name="no1">基础节点</param>
        ///// <param name="no2">被对比节点</param>
        ///// <param name="xmlConfigModels">对比配置</param>
        ///// <param name="result">结果值</param>
        //public void CompareNode(XmlNode templateNode, XmlNode no1, XmlNode no2, List<OptimizeSameNodeXL> xmlConfigModels, XmlNode result)
        //{
        //    foreach (XmlNode nodetemplate in templateNode.ChildNodes)
        //    {
        //        string xmlpath = base.GetXmlPath(nodetemplate);
        //        //默认将当前节点路径赋值节点查询路径
        //        string rootpath = xmlpath;
        //        if (templateNode.Name != "事实要素")
        //        {
        //            rootpath = xmlpath.Substring(xmlpath.LastIndexOf('/') + 1);
        //        }
        //        XmlNodeList nobase = no1.SelectNodes(rootpath);
        //        XmlNodeList nodetwo = no2.SelectNodes(rootpath);
        //        OptimizeSameNodeXL xmlConfigModel = xmlConfigModels.FirstOrDefault(con => con.Xmlpath == xmlpath);
        //        if (nobase != null && nobase.Count > 0 && nodetwo != null && nodetwo.Count > 0)
        //        {  //判定存在当前节点信息
        //            if (xmlConfigModel != null && xmlConfigModel.Overall == "1")
        //            {//当前节点为整体处理方式
        //                bool isMergenode = true;
        //                if (nobase.Count != nodetwo.Count)
        //                {//如果节点不相同，则直接进行导入
        //                    isMergenode = false;
        //                }
        //                else
        //                {//如果节点数量相同，则进行处理遍历对比是否相同
        //                    foreach (XmlNode no_one in nobase)
        //                    {
        //                        foreach (XmlNode no_two in nodetwo)
        //                        {
        //                            bool issameNode = base.IsSameNode(xmlConfigModel, no_one, no_two);
        //                            if (!issameNode)
        //                            {//如果节点相同
        //                                isMergenode = false;
        //                            }

        //                        }
        //                    }
        //                }
        //                if (!isMergenode)
        //                {
        //                    foreach (XmlNode no_one in nobase)
        //                    {
        //                        XmlNode newnod = result.OwnerDocument.ImportNode(no_one, true);
        //                        result.AppendChild(newnod);
        //                    }
        //                }

        //            }
        //            else
        //            {
        //                foreach (XmlNode no_one in nobase)
        //                {
        //                    foreach (XmlNode no_two in nodetwo)
        //                    {
        //                        bool issameNode = base.IsSameNode(xmlConfigModel, no_one, no_two);
        //                        if (issameNode)
        //                        {//如果节点相同
        //                            XmlNode newnod = result.OwnerDocument.CreateElement(no_one.Name);
        //                            foreach (XmlAttribute attr1 in no_one.Attributes)
        //                            {
        //                                XmlAttribute att2 = no_two.Attributes.Cast<XmlAttribute>().ToList().FirstOrDefault(at2 => at2.Name == attr1.Name);
        //                                if (att2 != null && att2.Value != attr1.Value)
        //                                {
        //                                    XmlAttribute attributet = (XmlAttribute)newnod.OwnerDocument.ImportNode(attr1, true);
        //                                    newnod.Attributes.Append(attributet);
        //                                }
        //                                //将标识属性进行添加到有异议节点中
        //                                if (xmlConfigModel != null)
        //                                {
        //                                    if (xmlConfigModel.Currentnote.Any(no => no.name == attr1.Name))
        //                                    {
        //                                        XmlAttribute attributet = (XmlAttribute)newnod.OwnerDocument.ImportNode(attr1, true);
        //                                        newnod.Attributes.Append(attributet);
        //                                    }
        //                                }

        //                            }
        //                            result.AppendChild(newnod);
        //                            //进行递归获取子节点信息
        //                            CompareNode(nodetemplate, no_one, no_two, xmlConfigModels, newnod);
        //                        }

        //                    }
        //                }
        //            }

        //        }
        //    }

        //}



        /// <summary>
        /// 进行节点的对比
        /// </summary>
        /// <param name="templateNode">模板节点</param>
        /// <param name="no1">基础节点</param>
        /// <param name="no2">被对比节点</param>
        /// <param name="xmlConfigModels">对比配置</param>
        /// <param name="result">结果值</param>
        /// <param name="nodeHandleType">同节点判定类型</param>
        public void CompareNode(XmlNode templateNode, XmlNode no1, XmlNode no2, List<SameNodeXml> xmlConfigModels, XmlNode result, SameNodeHandleType nodeHandleType)
        {
            foreach (XmlNode nodetemplate in templateNode.ChildNodes)
            {
                string xmlpath = base.GetXmlPath(nodetemplate);
                //默认将当前节点路径赋值节点查询路径
                string rootpath = xmlpath;
                if (templateNode.Name != "事实要素")
                {
                    rootpath = xmlpath.Substring(xmlpath.LastIndexOf('/') + 1);
                }
                XmlNodeList nobase = no1.SelectNodes(rootpath);
                XmlNodeList nodetwo = no2.SelectNodes(rootpath);
                SameNodeXml xmlConfigModel = xmlConfigModels.FirstOrDefault(con => con.XmlPath == xmlpath);
                if (nobase != null && nobase.Count > 0 && nodetwo != null && nodetwo.Count > 0)
                {  //判定存在当前节点信息
                    if (xmlConfigModel != null && xmlConfigModel.OverAll == "1")
                    {//当前节点为整体处理方式
                        bool isMergenode = true;
                        if (nobase.Count != nodetwo.Count)
                        {//如果节点不相同，则直接进行导入
                            isMergenode = false;
                        }
                        else
                        {//如果节点数量相同，则进行处理遍历对比是否相同
                            foreach (XmlNode no_one in nobase)
                            {
                                foreach (XmlNode no_two in nodetwo)
                                {
                                    bool issameNode = base.IsSameNode(xmlConfigModel, no_one, no_two, nodeHandleType);
                                    if (!issameNode)
                                    {//如果节点相同
                                        isMergenode = false;
                                    }

                                }
                            }
                        }
                        if (!isMergenode)
                        {
                            foreach (XmlNode no_one in nobase)
                            {
                                XmlNode newnod = result.OwnerDocument.ImportNode(no_one, true);
                                result.AppendChild(newnod);
                            }
                        }

                    }
                    else
                    {
                        foreach (XmlNode no_one in nobase)
                        {
                            foreach (XmlNode no_two in nodetwo)
                            {
                                bool issameNode = base.IsSameNode(xmlConfigModel, no_one, no_two, nodeHandleType);
                                if (issameNode)
                                {//如果节点相同
                                    XmlNode newnod = result.OwnerDocument.CreateElement(no_one.Name);
                                    foreach (XmlAttribute attr1 in no_one.Attributes)
                                    {
                                        XmlAttribute att2 = no_two.Attributes.Cast<XmlAttribute>().ToList().FirstOrDefault(at2 => at2.Name == attr1.Name);
                                        if (att2 != null && att2.Value != attr1.Value)
                                        {
                                            XmlAttribute attributet = (XmlAttribute)newnod.OwnerDocument.ImportNode(attr1, true);
                                            newnod.Attributes.Append(attributet);
                                        }
                                        //将标识属性进行添加到有异议节点中
                                        if (xmlConfigModel != null)
                                        {
                                            var handtype = xmlConfigModel.HandleTypes.FirstOrDefault(m => m.Code.Contains(nodeHandleType.ToString()));
                                            if (handtype != null)
                                            {
                                                if (handtype.CurrentNote.Any(no => no.Name == attr1.Name))
                                                {
                                                    XmlAttribute attributet = (XmlAttribute)newnod.OwnerDocument.ImportNode(attr1, true);
                                                    newnod.Attributes.Append(attributet);
                                                }
                                            }

                                        }

                                    }
                                    result.AppendChild(newnod);
                                    //进行递归获取子节点信息
                                    this.CompareNode(nodetemplate, no_one, no_two, xmlConfigModels, newnod, nodeHandleType);
                                }

                            }
                        }
                    }

                }
            }

        }


        /// <summary>
        /// 进行将当前的去除空节点对外发布
        /// </summary>
        /// <param name="docxml">待处理对象</param>
        /// <returns></returns>
        public new XmlDocument EscapeNodeIndexAndBlank(XmlDocument docxml)
        {
            //去除空节点
            return base.EscapeNodeIndexAndBlank(docxml);
        }


    }
}
